const cloud = require('@alipay/faas-server-sdk');
cloud.init();
const db = cloud.database();
exports.main = async (event, context) => {

  var action = event.action;
  var openid = event.openId;
  console.log("users openid", event);

  //测试代码会自动创建集合，真实项目应该提前创建好
  try {
    await db.createCollection("fund_info");
  } catch (error) {
    console.log("users 结合已经存在，无需再进行创建");
  }
  //添加用户，如果逻辑比较复杂，可以单独再写一个 addUser 函数
  if (action == 'addFundInfo') {

    const fundInfo = await db.collection("fund_info").where({
      _openid: event.openId,
      fundCode: event.fundCode
    }).get();
    console.log("fundInfo", fundInfo);
    if (fundInfo.length === 0) {
      await db.collection("fund_info").add({
        data: {
          fundAmt: event.fundAmt,
          fundName: event.fundName,
          fundCode: event.fundCode,
          fundCount: event.fundCount,
          fixDate: event.fixDate,
          todayAmt: event.todayAmt,
        },
      });

    } else {
      await db
        .collection('fund_info')
        .doc(users[0]._id)
        .update({
          data: {
            fundAmt: event.fundAmt,
            fundName: event.fundName,
            fundCode: event.fundCode,
            fundCount: event.fundCount,
            fixDate: event.fixDate,
            todayAmt: event.todayAmt,
          },
        });

    }


    //添加用户成功
    return {
      "message": "创建用户成功!",
      success: true
    };

  } else if (action == "getAllFundInfosByopenId") {
    //查询全部用户，默认返回100条，生成环境应该进行分页
    const users = await db.collection("fund_info").where({
      _openid: event.openId
    }).get();
    //查询用户成功
    return {
      "message": "查询成功!",
      success: true,
      data: users
    };

  }
  return {
    "message": "操作未识别!",
    success: false
  };
};